package com.iotechn.unimall.admin.api.warehouseOperLog;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.iotechn.unimall.core.exception.ServiceException;
import com.iotechn.unimall.data.domain.WarehouseDO;
import com.iotechn.unimall.data.domain.WarehouseOperLogDO;
import com.iotechn.unimall.data.mapper.WarehouseMapper;
import com.iotechn.unimall.data.mapper.WarehouseOperLogMapper;
import com.iotechn.unimall.data.model.Page;
import com.iotechn.unimall.data.util.SessionUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class WarehouseOperLogServiceImpl implements WarehouseOperLogService {
    @Autowired
    private WarehouseOperLogMapper warehouseOperLogMapper;
    @Autowired
    private WarehouseMapper warehouseMapper;

    @Override
    public Page<WarehouseOperLogDO> list(Integer page, Integer limit, String title, String timeInfo,
                                         Long adminId, Long skuId,Long warehouseId) throws ServiceException {
        Long id = SessionUtil.getAdmin().getId();
        List<WarehouseDO> warehouseDOS = warehouseMapper.selectList(new EntityWrapper<WarehouseDO>().eq("admin_id", id));
        List<Long> warehouseIds = warehouseDOS.stream().map(WarehouseDO::getId).collect(Collectors.toList());
        Wrapper<WarehouseOperLogDO> wrapper = new EntityWrapper<WarehouseOperLogDO>();
        if (!StringUtils.isEmpty(timeInfo)) {
            String[] startTime=timeInfo.split(",");
            wrapper.between("gmt_create", startTime[0], startTime[1]);
        }
        if (warehouseId != null) {
            wrapper.in("warehouse_id", warehouseIds);
        }else{
            warehouseIds =new ArrayList<>();
            warehouseIds.add(warehouseId);
            wrapper.in("warehouse_id", warehouseIds);
        }
        if (skuId != null) {
            wrapper.eq("sku_id", skuId);
        }
        if (!StringUtils.isEmpty(title)) {
            wrapper.andNew().like("spu_name", title).or().like("sku_no", title);
        }
        wrapper.orderBy("id", false);
        Integer count = warehouseOperLogMapper.selectCount(wrapper);
        List<WarehouseOperLogDO> WarehouseOperLogDOS = warehouseOperLogMapper.selectPage(new RowBounds((page - 1) * limit, limit), wrapper);
        return new Page<>(WarehouseOperLogDOS, page, limit, count);
    }

    @Override
    public WarehouseOperLogDO detail(Long id, Long adminId) throws ServiceException {
        return warehouseOperLogMapper.selectById(id);
    }

}